Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Microsoft.Extensions.AI support #64

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

HavenDV
Copy link
Contributor

@HavenDV HavenDV commented Nov 1, 2024

https://github.com/dotnet/extensions/tree/main/src/Libraries/Microsoft.Extensions.AI.Abstractions
https://devblogs.microsoft.com/dotnet/introducing-microsoft-extensions-ai-preview/
awaescher/OllamaSharp#111

Summary by CodeRabbit

  • New Features

    • Added support for the Microsoft.Extensions.AI library in the README.
    • Introduced the OllamaApiClient class with methods for chat interactions, including CompleteAsync for chat completion.
  • Documentation

    • Updated the README to reflect new features and integrations.
  • Chores

    • Enhanced package categorization by updating package tags and adding a reference to Microsoft.Extensions.AI.Abstractions.

Copy link

coderabbitai bot commented Nov 1, 2024

Walkthrough

The changes in this pull request introduce enhancements to the documentation and project structure of the Ollama library. The README.md file is updated to include support for the Microsoft.Extensions.AI library in the "Features" section. Additionally, the Ollama.csproj project file is modified to include new package tags and a reference to the Microsoft.Extensions.AI.Abstractions package. A new file, OllamaApiClient.IChatClient.cs, is added, which implements the IChatClient interface, providing methods for chat completion and streaming.

Changes

File Change Summary
README.md Added support for Microsoft.Extensions.AI in the "Features" section.
src/libs/Ollama/Ollama.csproj Updated PackageTags to include ai, abstractions, llama, ichatclient; added package reference for Microsoft.Extensions.AI.Abstractions version 9.0.0-preview.9.24507.7.
src/libs/Ollama/OllamaApiClient.IChatClient.cs Added OllamaApiClient class implementing IChatClient, with methods CompleteAsync and CompleteStreamingAsync, and a GetService<TService> method.

Possibly related PRs

🐰 In the meadow, changes bloom,
New features sprout, dispelling gloom.
With AI's grace, our chat's refined,
In code and docs, new paths we find.
Hops of joy in every line,
Ollama's magic, truly divine! 🌼


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions github-actions bot enabled auto-merge November 1, 2024 17:13
@HavenDV HavenDV disabled auto-merge November 1, 2024 17:15
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Outside diff range and nitpick comments (1)
README.md (1)

15-15: Consider adding usage examples for Microsoft.Extensions.AI integration.

While the feature is documented in the Features section, it would be helpful to add usage examples demonstrating how to use the Microsoft.Extensions.AI integration, similar to the existing examples for other features.

Would you like me to help generate usage examples for the Microsoft.Extensions.AI integration?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0c31a0d and 062f3f3.

📒 Files selected for processing (3)
  • README.md (1 hunks)
  • src/libs/Ollama/Ollama.csproj (1 hunks)
  • src/libs/Ollama/OllamaApiClient.IChatClient.cs (1 hunks)
🔇 Additional comments (5)
src/libs/Ollama/Ollama.csproj (2)

15-15: LGTM! Package tags accurately reflect new AI capabilities.

The added tags (ai, abstractions, llama, ichatclient) appropriately describe the new Microsoft.Extensions.AI integration.


20-20: Verify compatibility of preview package with target frameworks.

The Microsoft.Extensions.AI.Abstractions package is currently in preview (9.0.0-preview.9) and targets .NET 9. This raises several concerns:

  1. Using preview packages in production code could lead to breaking changes
  2. Need to verify compatibility with older target frameworks (netstandard2.0, net4.6.2)

Consider:

  • Adding conditional package references based on target framework
  • Documenting the preview status in README
  • Having a plan to update when the stable version is released
✅ Verification successful

Let me gather more information about the target frameworks and package references.


Let me gather more information about the AI abstractions package usage.


Based on the analysis of the codebase, I can now provide a final response:

Preview package usage is appropriate for this implementation

The Microsoft.Extensions.AI.Abstractions package is used appropriately in this context because:

  1. The project properly implements the IChatClient interface from the package
  2. The project supports multiple target frameworks (netstandard2.0, net4.6.2, net8.0) as defined in the csproj
  3. The package is only used for interface implementation, which is framework-agnostic
  4. The preview status is already documented in the README.md

The preview package doesn't pose compatibility risks since:

  • The implementation is focused on interface contracts rather than framework-specific features
  • The project uses conditional compilation (#if NET8_0_OR_GREATER) to handle framework-specific code
  • PolySharp is included to handle polyfills for older frameworks
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if there are any documented known issues or breaking changes
rg -A 5 "Microsoft\.Extensions\.AI" README.md CHANGELOG.md docs/

# Look for any conditional compilation or framework checks related to this feature
ast-grep --pattern 'if NETSTANDARD || NET462 {
  $$$
}'

Length of output: 389


Script:

#!/bin/bash
# Check target frameworks in the project file
cat src/libs/Ollama/Ollama.csproj

# Check for any conditional package references or framework-specific code
rg -g "*.cs" -B 2 -A 2 "#if" src/libs/Ollama/

# Look for any framework-specific implementations
ast-grep --pattern 'namespace $_ {
  $$$
  #if $_
  $$$
  #endif
  $$$
}'

Length of output: 79561


Script:

#!/bin/bash
# Check for AI abstractions usage in the codebase
rg -g "*.cs" -B 2 -A 2 "Microsoft\.Extensions\.AI" src/

# Check for any framework-specific implementations or interfaces
ast-grep --pattern 'interface $_ : Microsoft.Extensions.AI.$_ {
  $$$
}'

Length of output: 612

README.md (1)

15-15: LGTM! Feature documentation added.

The addition of Microsoft.Extensions.AI support in the Features section is clear and includes a link to the official documentation.

src/libs/Ollama/OllamaApiClient.IChatClient.cs (2)

34-34: Verify handling of null Temperature in RequestOptions

When options is null or options.Temperature is not set, Temperature will be null. Ensure that the RequestOptions object and the downstream processing can handle a null Temperature appropriately, or provide a default value to maintain expected behavior.


29-31: Confirm default behavior for ResponseFormat when null

If options?.ResponseFormat does not match ChatResponseFormatJson, the format parameter is set to null. Verify that passing a null format to GenerateChatCompletionAsync is acceptable and that it triggers the intended default behavior in the API.

ChatOptions? options = null,
CancellationToken cancellationToken = default)
{
throw new NotImplementedException();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Implement CompleteStreamingAsync method

The CompleteStreamingAsync method currently throws a NotImplementedException. Since this method is part of the IChatClient interface, it should be properly implemented to fulfill the contract and avoid runtime exceptions.

Would you like assistance in implementing the CompleteStreamingAsync method?

Parameters = x.AsJson(),
},
}).ToList(),
cancellationToken: cancellationToken).WaitAsync().ConfigureAwait(false);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Review the use of WaitAsync with ConfigureAwait(false)

Using WaitAsync() in combination with await and ConfigureAwait(false) may be unnecessary and could introduce complexity. Consider removing WaitAsync() to simplify the code unless there is a specific need for it.

Apply this diff to streamline the await statement:

-            cancellationToken: cancellationToken).WaitAsync().ConfigureAwait(false);
+            cancellationToken: cancellationToken).ConfigureAwait(false);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
cancellationToken: cancellationToken).WaitAsync().ConfigureAwait(false);
cancellationToken: cancellationToken).ConfigureAwait(false);

Comment on lines +18 to +25
Role = x.Role.Value switch
{
"assistant" => MessageRole.Assistant,
"user" => MessageRole.User,
"system" => MessageRole.System,
"tool" => MessageRole.Tool,
_ => MessageRole.User,
},
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Handle potential null values in x.Role

The code uses x.Role.Value without verifying if x.Role or x.Role.Value is null. This could lead to a NullReferenceException if x.Role is null. To prevent this, consider adding a null-conditional operator or a null check.

Apply this diff to safely access x.Role.Value:

-                    Role = x.Role.Value switch
+                    Role = (x.Role?.Value) switch
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
Role = x.Role.Value switch
{
"assistant" => MessageRole.Assistant,
"user" => MessageRole.User,
"system" => MessageRole.System,
"tool" => MessageRole.Tool,
_ => MessageRole.User,
},
Role = (x.Role?.Value) switch
{
"assistant" => MessageRole.Assistant,
"user" => MessageRole.User,
"system" => MessageRole.System,
"tool" => MessageRole.Tool,
_ => MessageRole.User,
},

Comment on lines +38 to +46
tools: options?.Tools?.Select(x => new Tool
{
Function = new ToolFunction
{
Name = string.Empty,
Description = string.Empty,
Parameters = x.AsJson(),
},
}).ToList(),
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Provide meaningful Name and Description for tools

Currently, the Name and Description properties of ToolFunction are set to string.Empty. This may not provide sufficient information for tool functionality. Consider populating these properties with relevant values from x to enhance clarity and utility.

Apply this diff to assign appropriate values:

                     Function = new ToolFunction
                     {
-                        Name = string.Empty,
-                        Description = string.Empty,
+                        Name = x.Name,
+                        Description = x.Description,
                         Parameters = x.AsJson(),
                     },

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +13 to +47
var response = await Chat.GenerateChatCompletionAsync(
model: options?.ModelId ?? "ollama",
messages: chatMessages.Select(x => new Message
{
Content = x.Text ?? string.Empty,
Role = x.Role.Value switch
{
"assistant" => MessageRole.Assistant,
"user" => MessageRole.User,
"system" => MessageRole.System,
"tool" => MessageRole.Tool,
_ => MessageRole.User,
},
}).ToArray(),
format: options?.ResponseFormat switch
{
ChatResponseFormatJson => ResponseFormat.Json,
_ => null,
},
options: new RequestOptions
{
Temperature = options?.Temperature,
},
stream: false,
keepAlive: default,
tools: options?.Tools?.Select(x => new Tool
{
Function = new ToolFunction
{
Name = string.Empty,
Description = string.Empty,
Parameters = x.AsJson(),
},
}).ToList(),
cancellationToken: cancellationToken).WaitAsync().ConfigureAwait(false);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Ensure response is not null before accessing its properties

Currently, the code checks if response.Message is null but does not verify if response itself is null. If Chat.GenerateChatCompletionAsync returns null, accessing response.Message will result in a NullReferenceException. Consider adding a null check for response to enhance robustness.

Apply this diff to add the null check:

+        if (response == null)
+        {
+            throw new InvalidOperationException("Response was null.");
+        }
         if (response.Message == null)
         {
             throw new InvalidOperationException("Response message was null.");
         }

Committable suggestion skipped: line range outside the PR's diff.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant